import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:async';
import 'dart:io';
import 'package:url_launcher/url_launcher.dart';
import '../models/banner.dart';
import '../widgets/load_image_widget.dart';

class BannerCarouselWidget extends StatefulWidget {
  final List<BannerItem> banners;
  final double height;

  const BannerCarouselWidget({
    Key? key,
    required this.banners,
    this.height = 180,
  }) : super(key: key);

  @override
  _BannerCarouselWidgetState createState() => _BannerCarouselWidgetState();
}

class _BannerCarouselWidgetState extends State<BannerCarouselWidget> {
  final PageController _pageController = PageController();
  Timer? _timer;
  int _currentPage = 0;

  @override
  void initState() {
    super.initState();
    print('BannerCarouselWidget initState with ${widget.banners.length} banners');
    _startAutoPlay();
  }

  @override
  void dispose() {
    _timer?.cancel();
    _pageController.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(BannerCarouselWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.banners.length != oldWidget.banners.length) {
      _startAutoPlay();
    }
  }

  void _startAutoPlay() {
    _timer?.cancel();
    if (widget.banners.length > 1) {
      print('Starting auto-play for ${widget.banners.length} banners');
      _timer = Timer.periodic(Duration(seconds: 3), (timer) {
        if (_pageController.hasClients) {
          int nextPage = (_currentPage + 1) % widget.banners.length;
          print('Auto-scrolling to page $nextPage');
          _pageController.animateToPage(
            nextPage,
            duration: Duration(milliseconds: 300),
            curve: Curves.easeIn,
          );
        } else {
          print('PageController has no clients');
        }
      });
    } else {
      print('Not starting auto-play: only ${widget.banners.length} banners');
    }
  }

  @override
  Widget build(BuildContext context) {
    print('Building BannerCarouselWidget with ${widget.banners.length} banners');

    // 打印每个轮播图的详细信息
    for (var banner in widget.banners) {
      print('Banner in widget: id=${banner.id}, url=${banner.imageUrl}');
    }

    if (widget.banners.isEmpty) {
      return Container(
        height: widget.height.h,
        color: Colors.grey[200],
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.image_not_supported_outlined, size: 40, color: Colors.grey),
              SizedBox(height: 8),
              Text(
                '暂无轮播图',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Container(
      height: widget.height.h,
      child: Stack(
        children: [
          // 轮播内容
          PageView.builder(
            controller: _pageController,
            itemCount: widget.banners.length,
            onPageChanged: (int page) {
              setState(() {
                _currentPage = page;
              });
            },
            itemBuilder: (context, index) {
              return _buildBannerItem(widget.banners[index]);
            },
          ),

          // 指示器
          Positioned(
            bottom: 10.h,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(
                widget.banners.length,
                    (index) => Container(
                  width: 8.w,
                  height: 8.w,
                  margin: EdgeInsets.symmetric(horizontal: 2.w),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: _currentPage == index
                        ? Colors.white
                        : Colors.white.withOpacity(0.5),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBannerItem(BannerItem banner) {
    return GestureDetector(
      onTap: () {
        _launchURL(banner.websiteUrl);
      },
      child: Stack(
        fit: StackFit.expand,
        children: [
          // 图片
          _buildImage(banner.imageUrl),
          // 半透明文字背景
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              color: Colors.black.withOpacity(0.3),
              padding: EdgeInsets.symmetric(
                horizontal: 12.w,
                vertical: 8.h,
              ),
              child: Text(
                banner.description,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _launchURL(String url) async {
    try {
      final Uri uri = Uri.parse(url);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      } else {
        print('Could not launch $url');
      }
    } catch (e) {
      print('Error launching URL: $e');
    }
  }

  Widget _buildImage(String imageUrl) {
    print('Building banner image with URL: $imageUrl');
    if (imageUrl.startsWith('/')) {
      // 本地文件路径
      return Image.file(
        File(imageUrl),
        fit: BoxFit.cover,
      );
    } else if (imageUrl.startsWith('http')) {
      // 网络图片
      return Image.network(
        imageUrl,
        fit: BoxFit.cover,
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return Center(
            child: CircularProgressIndicator(
              value: loadingProgress.expectedTotalBytes != null
                  ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
                  : null,
            ),
          );
        },
        errorBuilder: (context, error, stackTrace) {
          print('Error loading image: $error');
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, color: Colors.red, size: 30),
                SizedBox(height: 8),
                Text('图片加载失败', style: TextStyle(color: Colors.red)),
              ],
            ),
          );
        },
      );
    } else {
      // 资源图片
      return Image.asset(
        imageUrl,
        fit: BoxFit.cover,
      );
    }
  }
}